package user.main;


import guiobjects.Observation;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Scanner;

import user.functions.PruningAlgorithm;

import commonfunctions.Functions;
import commonfunctions.Matrix;

/**
 * Parses a matrix of weights.
 * 
 * @author Trevor Terris
 *
 */
public class RunMatrixParsing 
{
	private static int numItems = 1000;
	private static int numPerFrame = 10;
	public static final String SIMPLE_VIEW_NAME = "simple-view.txt";
	public static void main (String[] args)
	{
		try	
		{
			Matrix weights = new Matrix(numItems);
			Scanner s = new Scanner(new File("input/Pij.m"));
			while (s.hasNext())
			{
				int i = s.nextInt() - 1;
				int j = s.nextInt() - 1;
				double weight = s.nextDouble();
				if (i < 1000 && j < 1000 && weight > 0.1)
					weights.set(weight, i, j);
			}
			System.out.println("pruning");
			Matrix tracks = PruningAlgorithm.prune(weights, new ArrayList<Observation>());
			createFile(weights, tracks, "input");
		}
		catch (Exception e)
		{
			System.out.println("Error.");
		}
	}

	public static void createFile(Matrix probabilities, Matrix trackedPath, String dirName)
	{
		try
		{
			int lastFrame = numItems / numPerFrame;
			int[] pathItsOn = new int[numItems];
			ArrayList<Integer> starts = Functions.trackStarts(trackedPath);
			int numRemoved = 0;
			for (int i = 0; i < starts.size(); i++)
			{
				if (i >= starts.size())
					break;
				boolean hasNext = false;
				for (int j = starts.get(i); j < numItems; j++)
				{
					if (trackedPath.getBoolean(starts.get(i), j))
					{
						hasNext = true;
					}
				}
				if(!hasNext)
				{
					starts.remove(i);
					numRemoved++;
					i--;
				}
			}
			File f = new File(dirName + "/" + SIMPLE_VIEW_NAME);
	        Writer output = null;
	        output = new BufferedWriter(new FileWriter(f));
	        output.flush();
	        for (int i = 0; i < trackedPath.length(); i++)
	        {
	        	for(int j = i + 1; j < trackedPath.length(); j++)
	        	{
	        		if (trackedPath.getBoolean(i, j))
	        		{
	        			int y = (starts.contains(i))?starts.indexOf(i):pathItsOn[i];
	        			pathItsOn[j] = y;
	        			double yVal = 0.01 + 0.98 * ((double)y)/((double)starts.size());
	        			double xStart = 0.05 + 0.90 * (double)(i / numPerFrame) / (double)lastFrame;
	        			double xEnd = 0.05 + 0.90 * (double)(i / numPerFrame) / (double)lastFrame;
						int width = (int)(probabilities.get(i, j) / 0.2) + 1;
	        			
	        			String toWrite = "Line 1 " + xStart + " " + yVal + " " + xEnd + " " + yVal + " 0 0 0 " + width + "\n";
	        			output.write(toWrite);
	        			break;
	        		}
	        	}
	        }
	        output.write("Text 1 0.0 1.0 Single-Point tracks: " + numRemoved);
	        output.close();
		}
		catch (Exception e)
		{
			System.out.println("Error.");
		}
	}
}
